﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

/// <summary>
/// 구글 시각화 API을 이용하여 스크립트를 생성하는 기능을 담당합니다.
/// </summary>
public class GoogleBizApi
{

    public GoogleBizApi()
    {
        
    }

    /// <summary>
    /// 구글 시각화 API 스크립트 템플릿
    /// @로 시작하는 문자열만 변경되므로 나중에 해당 자료로 replace되면 실행 가능한 자바스크립트 소스로 변환됨
    /// </summary>
    private const string ScriptTemplate_table = @"
                    <script type='text/javascript'>
                      var data;
                      var table;
                      var columnChart;
                      var param_year = document.getElementById('ddlYear').value;
                      google.load('visualization', '1', {packages:['@PackagesGoogleVizType']});
                      google.setOnLoadCallback(drawGoogleViz);
                      function drawGoogleViz() {
                        data = new google.visualization.DataTable();

                        data.addRows(@RowCount);

                        @GoogleVizdata

                        table = new google.visualization.@MethodGoogleVizType(document.getElementById('@DrawAreaControlName'));
                        table.draw(data, {@DrawOption});
                        google.visualization.events.addListener(table, 'select', selectHandler_table);
                      }

                      function selectHandler_table() {
                        var selection = table.getSelection();
                        var message = '';
                        var str='';
                        if (selection.length==1){
                              var item = selection[0];
                              if (item.row != null && item.column != null) {
                                str = data.getFormattedValue(item.row, item.column);
                              } else if (item.row != null) {
                                str = data.getFormattedValue(item.row, 0);
                              } else if (item.column != null) {
                                str = data.getFormattedValue(0, item.column);
                              }

		                   var go_url = 'historyView.aspx?Region='+escape(str);
		                   window.open(go_url,'HistoryPop','resizable=1,scrollbars=1 ,width=1020,height=620');

                        } else {
                            alert('1개의 자료만 선택하여 주십시오.');
                        }

                      }
                    </script>
            ";

    private const string ScriptTemplate_columnChart = @"
                    <script type='text/javascript'>
                      google.load('visualization', '1', {packages:['@PackagesGoogleVizType']});
                      google.setOnLoadCallback(drawGoogleViz);
                      function drawGoogleViz() {
                        data = new google.visualization.DataTable();
                        data.addRows(@RowCount);

                        @GoogleVizdata

                        columnChart = new google.visualization.@MethodGoogleVizType(document.getElementById('@DrawAreaControlName'));
                        columnChart.draw(data, {@DrawOption});
                        google.visualization.events.addListener(columnChart, 'select', selectHandler_columnChart);
                      }

                      function selectHandler_columnChart() {
                        var selection = columnChart.getSelection();
                        var str='';
                        if (selection.length==1){
                              var item = selection[0];
                              if (item.row != null && item.column != null) {
                                str = data.getFormattedValue(item.row, 0);
                              } else if (item.row != null) {
                                str = data.getFormattedValue(item.row, 0);
                              } else if (item.column != null) {
                                str = data.getFormattedValue(0, item.column);
                              }

		                   var go_url = 'historyView.aspx?Region='+escape(str);
		                   window.open(go_url,'HistoryPop','resizable=1,scrollbars=1 ,width=1020,height=620');

                        } else {
                            alert('1개의 자료만 선택하여 주십시오.');
                        }

                      }
                    </script>
            ";

    private const string ScriptTemplate = @"
                    <script type='text/javascript'>
                      google.load('visualization', '1', {packages:['@PackagesGoogleVizType']});
                      google.setOnLoadCallback(drawGoogleViz);
                      function drawGoogleViz() {

                        data = new google.visualization.DataTable();
                        data.addRows(@RowCount);

                        @GoogleVizdata

                        var chartApi = new google.visualization.@MethodGoogleVizType(document.getElementById('@DrawAreaControlName'));
                        chartApi.draw(data, {@DrawOption});
                      }

                    </script>
            ";

    private string GoogleVizHtml;

    private int RowCount;

    private StringBuilder GoogleVizData = new StringBuilder();

    string[] ColumnTypes;
    string[] ColumnTitles;


    /// <summary>
    /// 헤더정보 저장
    /// 콤마로 구분된 자료, datatype:타이틀 형태
    /// 구글 api 첫번째 헤더 정보인 addColumn호출하기위함
    /// </summary>
    /// <param name="strRow">헤더자료</param>
    public void AddColumn(string strRow)
    {
        string[] arrColumnInfo = strRow.Split(',');

        ColumnTypes = new string[arrColumnInfo.Length];
        ColumnTitles = new string[arrColumnInfo.Length];

        for (int i = 0; i < arrColumnInfo.Length; i++)
        {
            ColumnTypes[i] = arrColumnInfo[i].Split(':')[0];
            ColumnTitles[i] = arrColumnInfo[i].Split(':')[1];

            GoogleVizData.Append(string.Format("data.addColumn('{0}', '{1}');" + Environment.NewLine, ColumnTypes[i], ColumnTitles[i]));
        }


    }

    /// <summary>
    /// 자료 설정
    /// 콤마로 구분된 자료, 자료 갯수만큼 호출
    /// setCell 호출하기 위함
    /// </summary>
    /// <param name="strRow">한행자료</param>
    public void SetCell(string strRow)
    {
        string[] arrColumnInfo = strRow.Split(',');

        
        for (int i = 0; i < arrColumnInfo.Length; i++)
        {
            //if(arrColumnInfo[i].Split(':').Length > 1)

            if (ColumnTypes[i].Equals("string", StringComparison.CurrentCultureIgnoreCase))
            {
                GoogleVizData.Append(string.Format("data.setCell({0}, {1}, '{2}');" + Environment.NewLine, RowCount.ToString(), i.ToString(), arrColumnInfo[i]));
            }
            else
            {
                GoogleVizData.Append(string.Format("data.setCell({0}, {1}, {2});" + Environment.NewLine, RowCount.ToString(), i.ToString(), arrColumnInfo[i]));
            }
        }


        RowCount++;
    }

    /// <summary>
    /// 위에서 설정된 자료에 따라 문자열 치환하여 스크립트 반환
    /// </summary>
    /// <param name="_PackagesType">api종류</param>
    /// <param name="_DrawAreaControlName">api가실행될div이름</param>
    /// <param name="_DrawOption">api옵션</param>
    /// <returns></returns>
    public string GetSource(string _PackagesType, string _DrawAreaControlName, string _DrawOption)
    {
        if (_PackagesType=="Table"){
            GoogleVizHtml = ScriptTemplate_table.Replace("@PackagesGoogleVizType", _PackagesType.ToLower());
        } else {
            GoogleVizHtml = ScriptTemplate_columnChart.Replace("@PackagesGoogleVizType", _PackagesType.ToLower());
        }
        GoogleVizHtml = GoogleVizHtml.Replace("@MethodGoogleVizType", _PackagesType);
        GoogleVizHtml = GoogleVizHtml.Replace("@DrawAreaControlName", _DrawAreaControlName);
        GoogleVizHtml = GoogleVizHtml.Replace("@DrawOption", _DrawOption);
        

        GoogleVizHtml = GoogleVizHtml.Replace("@RowCount", RowCount.ToString());

        GoogleVizHtml = GoogleVizHtml.Replace("@GoogleVizdata", GoogleVizData.ToString());

        
        
        return GoogleVizHtml;
    }

    /// <summary>
    /// 위에서 설정된 자료에 따라 문자열 치환하여 스크립트 반환
    /// </summary>
    /// <param name="_PackagesType">api종류</param>
    /// <param name="_DrawAreaControlName">api가실행될div이름</param>
    /// <param name="_DrawOption">api옵션</param>
    /// <returns></returns>
    public string GetSourceView(string _PackagesType, string _DrawAreaControlName, string _DrawOption)
    {
        GoogleVizHtml = ScriptTemplate.Replace("@PackagesGoogleVizType", _PackagesType.ToLower());
        GoogleVizHtml = GoogleVizHtml.Replace("@MethodGoogleVizType", _PackagesType);
        GoogleVizHtml = GoogleVizHtml.Replace("@DrawAreaControlName", _DrawAreaControlName);
        GoogleVizHtml = GoogleVizHtml.Replace("@DrawOption", _DrawOption);


        GoogleVizHtml = GoogleVizHtml.Replace("@RowCount", RowCount.ToString());

        GoogleVizHtml = GoogleVizHtml.Replace("@GoogleVizdata", GoogleVizData.ToString());



        return GoogleVizHtml;
    }
}
